﻿using Microsoft.EntityFrameworkCore;
using Tszy.Unlimited.Base.Common;

namespace Tszy.Unlimited.Data.EntityFramework;

/// <summary>
/// EntityFramework 上下文基类。
/// </summary>
public abstract class MainEntityFrameworkContext : DbContext, IEntityFrameworkContext
{
    /// <summary>
    /// 初始化。
    /// </summary>
    protected MainEntityFrameworkContext() : base() { }

    /// <summary>
    /// 初始化。
    /// </summary>
    /// <param name="options">配置信息。</param>
    protected MainEntityFrameworkContext(DbContextOptions options) : base(options) { }

    /// <summary>
    /// 唯一标识。
    /// </summary>
    public Guid UniqueId { get; } = IdentityGenerator.NewSequentialGuid();

    /// <summary>
    /// 将所有运行中的程序集注册到 EF 中。
    /// </summary>
    /// <param name="modelBuilder"></param>
    protected virtual void RegisterAssemblies(ModelBuilder modelBuilder)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("Microsoft"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("System"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("MySql"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.Contains("Serilog"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("MediatR"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.Contains("netstandard"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.Contains("Anonymously Hosted DynamicMethods Assembly"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("Tszy.Unlimited"))
                                  .Where(item => !string.IsNullOrWhiteSpace(item.FullName) && !item.FullName.StartsWith("Newtonsoft.Json"));

        if (!assemblies.Any())
            return;

        foreach (var assembly in assemblies)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(assembly);
        }
    }
}